package com.starbaba.core.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpClient {
    private URL url;
    private HttpURLConnection urlconn;

    String inencoding;
    
    public HttpClient(String inencoding) {
        this.inencoding = inencoding;
    }
    
    public String connect(String postUrl,int timeout) throws Exception {
        BufferedReader br = null;
        String response = "", brLine = "";
        try {
            url = new URL(postUrl);
            urlconn = (HttpURLConnection) url.openConnection();
            urlconn.setRequestProperty("user-agent","mozilla/4.7 [en] (win98; i)");    //set request header 
            urlconn.setRequestProperty("X-Forwarded-For", "127.0.0.1");
            urlconn.setConnectTimeout(timeout);
            urlconn.setReadTimeout(30000);
            urlconn.setRequestMethod("POST");     // request method, default GET
            urlconn.setUseCaches(false);    //Post can not user cache
            urlconn.setDoOutput(false);    //set output from urlconn
            urlconn.setDoInput(true);    //set input from urlconn
            br = new BufferedReader(new InputStreamReader(urlconn.getInputStream(), inencoding));
            while((brLine = br.readLine())!=null)
                response =(new StringBuilder(String.valueOf(response))).append(brLine).toString();
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if(br != null) {
                    br.close();
                }
            } catch (IOException e) {
                System.out.println("input stream close fail");
            }
            urlconn.disconnect();
        }
        return response;
    }

//    public static void main(String[] args) {
//    	HttpClient tc = new HttpClient("UTF-8");
//        String response = tc.connect("http://10.245.245.4:8081/stconnector/connectorface/connectorFace!sendByHttp.action?cmdId=20303&datatrans=13509889587~DSTAAZHY0001~9",30000);
//        System.out.println(response);
//    }
}
